package com.an.pay.controller;


import com.an.pay.annotation.AliPayNotify;
import com.an.pay.client.AliPayClient;
import com.an.pay.entity.*;
import com.an.pay.enums.OrderStatus;
import com.an.pay.enums.PayType;
import com.an.pay.service.OrderInfoService;
import com.an.pay.service.ProductService;
import com.an.pay.service.RefundInfoService;
import com.an.pay.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/ali-pay")
@Api(tags = "支付宝支付api接口管理")
@Slf4j
public class AliPayController {

    @Autowired
    private AliPayClient aliPayClient;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RefundInfoService refundInfoService;

    @ApiOperation("支付宝下单")
    @PostMapping("/trade/page/pay/{productId}")
    public R pay(@PathVariable Long productId) throws Exception {
        // 获取商品信息
        Product product = productService.getById(productId);
        // 创建订单
        Map<String, String> map = orderInfoService.pay(productId, PayType.ALIPAY.getType());

        return R.ok().setData(map);
    }

    @ApiOperation("支付宝异步通知")
    @PostMapping("/trade/notify")
    @AliPayNotify
    public String notify(@RequestParam Map<String,String> map,String orderNo){
        log.info("orderNo==:{}",orderNo);
        // 查询订单信息
        OrderInfo orderInfo = orderInfoService.getOne(new QueryWrapper<OrderInfo>().eq("order_no",orderNo));
        log.info("orderInfo=={}",orderInfo);
        AliParams aliParams = AliParams.builder()
                .total(orderInfo.getTotalFee())
                .outTradeNo(orderNo)
                .build();

        // 验证通知参数
        String body = aliPayClient.aliPayNotify(map, aliParams);
        log.info("body==={}",body);
        if("success".equals(body)){
            // 通知参数验证成功
            // 修改订单状态
            OrderInfo order = new OrderInfo();
            order.setOrderStatus(OrderStatus.SUCCESS.getType());
            orderInfoService.update(order,new QueryWrapper<OrderInfo>().eq("order_no",orderNo));
            // 保存支付日志
        }
        return body;
    }

    @ApiOperation("申请退款")
    @PostMapping("/trade/refund/{orderNo}/{reason}")
    public R refunds(@PathVariable String orderNo, @PathVariable String reason){
        refundInfoService.refund(orderNo,reason,PayType.ALIPAY.getType());
        return R.ok();
    }


}
